package com.tianxinweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianxinweb.config.UploadConfig;
import com.tianxinweb.entity.Information;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import com.tianxinweb.mapper.InformationMapper;
import com.tianxinweb.service.InformationService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tianxinweb.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cboy
 * @since 2018-08-07
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements InformationService {

    @Autowired
    private UploadConfig uploadConfig;

    @Override
    public Page getInfoList(Integer pn, Integer size, String key) {
        if("".equals(key.trim())){
            return selectPage(new Page<>(pn,size));
        }else{
            return selectPage(new Page<>(pn,size),
                    new EntityWrapper<Information>().like("title",key));
        }
    }

    @Override
    public List<Information> getRecommendInfo() {
        return selectList(new EntityWrapper<Information>().eq("recommend",true));
    }

    @Override
    public void recommend(Integer id, Integer type) {
        Information information = selectById(id);
        if(information==null) throw new MyException(ResultEnum.FAILE);
        if(type==0){
            information.setRecommend(false);
        }else{
            information.setRecommend(true);
        }
        updateById(information);
    }

    @Override
    public void addReadingAmount(Integer id) {
        updateForSet("reading_amount=reading_amount+1",new EntityWrapper<Information>().eq("id",id));
    }

    @Override
    public void addInfo(Information info) {

        String imgUrl = info.getImageurl();
        if(imgUrl==null || "".equals(imgUrl))
            throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        String path = ImageUtil.moveFile(uploadConfig.getPath()+"/temp/"+imgUrl,uploadConfig.getPath()+"/info/");
        info.setImageurl("/info/"+path);
        info.setCreateTime(null);
        info.setRecommend(null);
        info.setDeleteFlag(null);
        insert(info);
    }

    @Override
    public void updateInfo(Information info) {
        Information dbInfo = selectById(info.getId());
        String imgUrl = info.getImageurl();
        if(imgUrl!=null && !"".equals(imgUrl)){
            String path = ImageUtil.moveFile(uploadConfig.getPath()+"/temp/"+imgUrl,uploadConfig.getPath()+"/info/");
            dbInfo.setImageurl("/info/"+path);
        }
        dbInfo.setTitle(info.getTitle());
        dbInfo.setDetail(info.getDetail());
        updateById(dbInfo);

    }
}
